package com.ido.otaclient.realtk;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.ido.otaclient.R;
import com.ido.otaclient.StatusDownload;
import com.ido.otaclient.api.OkhttpUtil;
import com.ido.otaclient.base.ApiConstant;
import com.ido.otaclient.base.Constant;
import com.ido.otaclient.base.IDLog;
import com.ido.otaclient.module.Veneer;
import com.ido.otaclient.util.AppExecutors;
import com.ido.otaclient.util.FileUtil;
import com.ido.otaclient.util.ResourceUtil;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2020-03-06 18:38
 * @description
 */
public class RealtkPresenter implements RealtkContract.Presenter{
    private static final String TAG = "RealtkPresenter";

    private RealtkContract.View mView;

    public RealtkPresenter(RealtkContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void uploadAndConfirmFile() {
        /**
         * 获得带有状态的单板列表
         */
        List<Veneer> veneerList = mView.getVeneerList();
        if(veneerList == null || veneerList.size() == 0){
            mView.showMessage(ResourceUtil.getString(R.string.veneer_not_found));
            return;
        }
        String filePath = mView.getFilePath();
        String fileVersion = mView.getChooseFileVersion();
        // todo 上传一个ip之后在上传另一个
        for(Veneer veneer : veneerList) {
            if (!TextUtils.isEmpty(veneer.getIp())) {
                Log.d(TAG,veneer.toString());
            }
        }
        mView.showLoading();
        //判断是否需要下发固件
        boolean isComplete = true;
        for(Veneer veneer : veneerList){
            IDLog.d(TAG, "uploadAndConfirmFile: " + veneer.toString());
            if(!TextUtils.isEmpty(veneer.getIp()) &&
                    veneer.getDownloadStatus() == StatusDownload.START.getCode()){
                //String url = ApiConstant.URL_HEAD + veneer.getIp() +":"+ Constant.HTTP_PORT;
                String url = ApiConstant.URL_HEAD + veneer.getIpPort();
                uploadFile(url,filePath,fileVersion,veneer.getIpPort());
                isComplete = false;
                break;
            }
        }
        if(isComplete){
            mView.hideLoading();
            saveUploadType();
        }
    }

    /**
     * 上传文件
     * @param url
     * @param filePath
     * @param fileVersion
     * @param ipPort
     */
    public void uploadFile(String url, String filePath, String fileVersion, String ipPort) {
        long size = FileUtil.getFileSize(filePath);
        String sizeStr = String.valueOf(size);

        AsyncHttpPost post = new AsyncHttpPost(url + "/upload");
        MultipartFormDataBody body = new MultipartFormDataBody();
        body.addFilePart("text.zip", new File(filePath));
        // 文件名传递
        body.addStringPart("foo", "upload.zip");
        post.setBody(body);
        AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
            @Override
            public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
                if (ex != null) {
                    mView.hideLoading();
                    //WaitingDialog.hideDialog();
                    AppExecutors.globalAppExecutors().mainThread().execute(()
                            -> updateVeneer(ipPort));
                    ex.printStackTrace();
                    return;
                }
                System.out.println("Server says: " + result);
                //确认成功
                confirmUploadFile(url,sizeStr,fileVersion,filePath,ipPort);
            }
        });
    }

    /**
     * 文件上传失败更新单板信息
     * @param ip 请求的ip
     */
    private void updateVeneer(String ip) {
        List<Veneer> veneerList = new ArrayList<>();
        veneerList.addAll(mView.getVeneerList());
        for(int i= 0;i < veneerList.size();i++){
            Veneer veneer = veneerList.get(i);
            if(ip.equals(veneer.getIp())){
                //veneer.setDownloadStatus(StatusDownload.COMPLETE.getCode());
                int failCount = veneer.getFailConnectCount();
                veneer.setFailConnectCount(++failCount);
                veneerList.set(i,veneer);
                mView.setVeneerList(veneerList);
            }
        }
        mView.showConfirmCancel();
    }

    public void confirmUploadFile(String url, String sizeStr, String fileVersion,
                                  String filePath, String ipPort) {
        IDLog.d(TAG, "confirmUploadFile: " + url + ","+ipPort);
        String name = FileUtil.getFileNameFromPath(filePath);
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("/");
        sb.append(ApiConstant.METHOD_CONFIRM_FIREWARE);
        sb.append("?");
        sb.append("size=");
        sb.append(sizeStr);
        sb.append("&");
        sb.append("taskType=");
        sb.append(Constant.TASK_NAME_REALTK);
        sb.append("&");
        sb.append("fileName=");
        sb.append(name);
        sb.append("&");
        sb.append("fileVersion=");
        sb.append(fileVersion);
        sb.append("&");
        sb.append("deviceId=");
        sb.append(mView.getDeviceId());
        url = sb.toString();
        OkhttpUtil okhttpUtil = OkhttpUtil.getInstance();
        okhttpUtil.getSyn(url, new OkhttpUtil.OkhttpCallback() {
            @Override
            public void onSuccess(String success) {
                /*Log.d(TAG, "onSuccess: " + success);
                Message message = new Message();
                message.what = 0;
                message.obj = success;*/
                List<Veneer> veneerList = new ArrayList<>();
                veneerList.addAll(mView.getVeneerList());
                for(int i= 0;i < veneerList.size();i++){
                    Veneer veneer = veneerList.get(i);
                    if(ipPort.equals(veneer.getIpPort())){
                        veneer.setDownloadStatus(StatusDownload.COMPLETE.getCode());
                        veneerList.set(i,veneer);
                        mView.setVeneerList(veneerList);
                    }
                }
                AppExecutors.globalAppExecutors().mainThread().execute(()
                        ->uploadAndConfirmFile());
            }

            @Override
            public void onFailed(String message) {
                //WaitingDialog.hideDialog();
                mView.hideLoading();
                Log.d(TAG,message);

                mView.showConfirmCancel();
            }
        });
    }

    /**
     * 保存
     */
    private void saveUploadType() {
        RealtkConfigPerfence realtkConfigPerfence = RealtkConfigPerfence.getInstance();
        String filePath = mView.getFilePath();
        String fileName = FileUtil.getFileNameFromPath(filePath);
        String fileVersion = mView.getChooseFileVersion();

        //保存realtkConfig 文件配置信息
        RealtkConfig  realtkConfig = new RealtkConfig();
        //保存
        realtkConfig.setTaskName(Constant.TASK_NAME_NORDIC);
        realtkConfig.setFirewareNormalName(fileName);
        realtkConfig.setFirewareNormalVersion(fileVersion);
        realtkConfig.setFirewareWarePath(mView.getFilePath());
        realtkConfig.setDeviceId(mView.getDeviceId());
        IDLog.d(TAG, "saveUploadType: " + realtkConfig.toString());
        realtkConfigPerfence.saveRealtkConfig(realtkConfig);
        mView.showMessage(ResourceUtil.getString(R.string.upload_file_success));
        mView.back();
    }

    @Override
    public void chooseFile(int requestCode, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        String fileFolder = Constant.DIR_OUT_SDCRA;
        File file = new File(fileFolder);
        if (file.exists()) {
            //从指定目录下选择文件 这个现在不知道能不能实现 现在还是查询所有目录下的
            Uri uri = FileUtil.getUriFromFile(activity, fileFolder);
            //Log.d(TAG, fileFolder + "," + uri.getPath());
            //intent.setDataAndType(uri, "*/*");
            intent.setType("*/*");
        } else {
            intent.setType("*/*");
        }
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(Activity act, int requestCode, int resultCode, Intent data) {
        if (data == null) {
            // 用户未选择任何文件，直接返回
            return;
        }
        String mPath = "";
        Uri uri = data.getData(); // 获取用户选择文件的URI
        if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
            mPath = uri.getPath();
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                mPath = FileUtil.getPath(act, uri);
            } else {//4.4以下下系统调用方法
                //path = FileUtil.getRealPathFromURI(this, uri);
            }
        }
        mView.setChooseDrawable();
        mView.showTvChooseFile(true);
        if(!TextUtils.isEmpty(mPath))
            mView.setFilePath(mPath);
        mView.setTvChooseFileName(FileUtil.getFileNameFromPath(mPath));
    }

    @Override
    public void confirmConfig() {
        String filePath = mView.getFilePath();
        String fileVersion = mView.getChooseFileVersion();
        if(TextUtils.isEmpty(filePath)){
            mView.showMessage(ResourceUtil.getString(R.string.upload_choose_file));
            return;
        }
        if(TextUtils.isEmpty(fileVersion)){
            mView.showMessage(ResourceUtil.getString(R.string.upload_input_version));
            return;
        }
        if(TextUtils.isEmpty(mView.getDeviceId())){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_device_id));
            return;
        }
        uploadAndConfirmFile();

    }

    @Override
    public void initConfig() {
        //保存nordic 文件配置信息
        RealtkConfigPerfence realtkConfigPerfence = RealtkConfigPerfence.getInstance();
        RealtkConfig realtkConfig = realtkConfigPerfence.getRealtkConfig();
        if(realtkConfig != null){
            IDLog.d(TAG, "initData: " + realtkConfig.toString());
            if(!TextUtils.isEmpty(realtkConfig.getFirewareNormalName())){
                mView.setChooseDrawable();
                mView.setFilePath(realtkConfig.getFirewareWarePath());
                mView.setTvChooseFileName(realtkConfig.getFirewareNormalName());
            }
            mView.showTvChooseFile(true);
            mView.setDeviceId(realtkConfig.getDeviceId());
            mView.setFileVersion(realtkConfig.getFirewareNormalVersion());
        }
    }

    @Override
    public void start() {

    }

    @Override
    public void release() {

    }
}
